<script setup lang="ts">
import { ref, onMounted } from 'vue';
import ArticleMenu from '@/components/article-menu.vue';
import ArticleTopBg from '@/components/article-top-bg.vue';
import { selectArticles, selectListCategory } from '@/api/article';
import type { ArticleInfo } from '@/types/article';
import { useRoute } from 'vue-router';
import { getCategoryArticle } from '@/api/category';
import type { Category, CategoryArticle } from '@/types/category.ts';
import LayoutFooter from '@/components/layout-footer.vue';
import {
  PhSpinner,
  PhFolder,
  PhCalendar,
  PhEye,
} from '@phosphor-icons/vue';
import { useWebConfigStore } from '@/stores';

const route = useRoute();
const categories = ref<Category[]>([]);
const articles = ref<ArticleInfo[]>([]);
const currentCategory = ref<string>('');
const categoryArticleList = ref<CategoryArticle[]>([]);
const loading = ref(true);
const webConfigStore = useWebConfigStore();

// 获取文章数据
const fetchArticleData = async () => {
  const id = route.query.id as string;
  currentCategory.value = id;
  return id ? await selectListCategory(id) : await selectArticles();
};

// 获取文章和分类数据
const fetchData = async () => {
  try {
    loading.value = true;
    const id = route.query.id as string;
    currentCategory.value = id;
    const articleResult = await fetchArticleData();
    articles.value = articleResult.data;
    // 统计分类
    const { data } = await getCategoryArticle();
    categoryArticleList.value = data;
    // 转换为分类数组
    categories.value = categoryArticleList.value.map(item => ({
      id: item.id,
      name: item.name,
      count: item.count,
      color: getRandomColor() // 为每个分类生成随机颜色
    }));
    const sum = categoryArticleList.value.reduce((sum, item) => sum += item.count, 0);
    // 添加"全部"分类
    categories.value.unshift({
      id: '0',
      name: '全部',
      count: sum,
      color: '#64748b'
    });
  } catch (err) {
    console.error('获取数据失败:', err);
  } finally {
    loading.value = false;
  }
};

// 生成随机颜色
const getRandomColor = () => {
  const colors = [
    '#3b82f6', '#10b981', '#f59e0b', '#8b5cf6',
    '#ec4899', '#6366f1', '#14b8a6', '#f43f5e'
  ];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 切换分类
const changeCategory = async (categoryId: string) => {
  if (categoryId === '0') {
    const { data } = await selectArticles();
    articles.value = data;
  } else {
    const { data } = await selectListCategory(categoryId);
    articles.value = data;
  }
  currentCategory.value = categoryId;
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="layout-container">
    <ArticleMenu />

    <ArticleTopBg
      height="600px"
      :title="webConfigStore.categoryTitle"
      :subtitles="webConfigStore.categorySubtitle"
      :background-images="webConfigStore.parsedCategoryCarousel"
      v-motion
      :initial="{ opacity: 0, y: 50 }"
      :enter="{ opacity: 1, y: 0, transition: { duration: 800 } }"
    />

    <div class="category-container">
      <!-- 分类标签列表 -->
      <div class="categories-wrapper"
           v-motion
           :initial="{ opacity: 0, y: 20 }"
           :enter="{ opacity: 1, y: 0, transition: { delay: 400 } }">
        <div class="categories">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-tag"
            :class="{ active: currentCategory === category.id }"
            :style="{ '--category-color': category.color }"
            @click="changeCategory(category.id)"
          >
            <span class="category-name">{{ category.name }}</span>
            <span class="category-count">{{ category.count }}</span>
          </div>
        </div>
      </div>

      <!-- 文章列表 -->
      <div class="articles-wrapper"
           v-motion
           :initial="{ opacity: 0, y: 20 }"
           :enter="{ opacity: 1, y: 0, transition: { delay: 600 } }">
        <div v-if="loading" class="loading-state">
          <PhSpinner :size="24" weight="bold" class="spin-icon" />
          <span>加载中...</span>
        </div>

        <div v-else-if="articles.length === 0" class="empty-state">
          <PhFolder :size="24" weight="bold" />
          <span>暂无文章</span>
        </div>

        <div v-else class="articles-grid">
          <router-link
            v-for="article in articles"
            :key="article.id"
            :to="`/detail/${article.slug}?id=${article.id}`"
            class="article-card"
            v-motion
            :initial="{ opacity: 0, y: 20 }"
            :enter="{ opacity: 1, y: 0 }"
          >
            <div class="article-cover" :style="{ backgroundImage: `url(${article.coverImage})` }">
              <div class="article-category" :style="{ backgroundColor: categories.find(c => c.name === article.categoryName)?.color }">
                {{ article.categoryName }}
              </div>
            </div>
            <div class="article-info">
              <h3 class="article-title">{{ article.title }}</h3>
              <p class="article-summary">{{ article.summary }}</p>
              <div class="article-meta">
                <span>
                  <PhCalendar :size="16" weight="bold" />
                  {{ article.publishTime }}
                </span>
                <span>
                  <PhEye :size="16" weight="bold" />
                  {{ article.views }}
                </span>
              </div>
            </div>
          </router-link>
        </div>
      </div>
    </div>

    <LayoutFooter />
  </div>
</template>
<style scoped lang="less">
.layout-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  .category-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 92px 12px 24px;
    width: 1161px;
    position: relative;
    z-index: 1;

    .categories-wrapper {
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(10px);
      border-radius: 16px;
      padding: 24px;
      margin-bottom: 24px;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

      .categories {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .category-tag {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 16px;
          border-radius: 20px;
          background: rgba(var(--category-color), 0.1);
          color: var(--category-color);
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
          }

          &.active {
            background: var(--category-color);
            color: white;
          }

          .category-count {
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.8em;
          }
        }
      }
    }

    .articles-wrapper {
      .loading-state,
      .empty-state {
        text-align: center;
        padding: 40px;
        color: #64748b;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;

        .spin-icon {
          animation: spin 1s linear infinite;
        }
      }

      .articles-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 24px;

        .article-card {
          background: rgba(255, 255, 255, 0.9);
          backdrop-filter: blur(10px);
          border-radius: 12px;
          overflow: hidden;
          box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
          transition: all 0.3s ease;
          text-decoration: none;
          color: inherit;

          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 20px -4px rgba(0, 0, 0, 0.15);
          }

          .article-cover {
            height: 200px;
            background-size: cover;
            background-position: center;
            position: relative;

            .article-category {
              position: absolute;
              top: 12px;
              left: 12px;
              padding: 4px 12px;
              border-radius: 12px;
              color: white;
              font-size: 0.9em;
            }
          }

          .article-info {
            padding: 20px;

            .article-title {
              font-size: 1.2em;
              font-weight: 600;
              margin-bottom: 12px;
              line-height: 1.4;
            }

            .article-summary {
              color: #64748b;
              font-size: 0.9em;
              line-height: 1.6;
              margin-bottom: 16px;
              display: -webkit-box;
              -webkit-line-clamp: 3;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .article-meta {
              display: flex;
              gap: 16px;
              color: #94a3b8;
              font-size: 0.85em;

              span {
                display: flex;
                align-items: center;
                gap: 6px;
              }
            }
          }
        }
      }
    }
  }
}

// 添加旋转动画
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media screen and (max-width: 1400px) {
  .layout-container .category-container {
    max-width: 1100px;
  }
}

@media screen and (max-width: 1200px) {
  .layout-container .category-container {
    max-width: 900px;
    padding: 72px 20px 24px;
  }
}

@media screen and (max-width: 992px) {
  .layout-container .category-container {
    max-width: 700px;

    .articles-grid {
      grid-template-columns: repeat(2, 1fr) !important;
    }
  }
}

@media screen and (max-width: 768px) {
  .layout-container .category-container {
    padding: 60px 16px 24px;

    .categories-wrapper {
      padding: 16px;

      .categories {
        gap: 8px;

        .category-tag {
          padding: 6px 12px;
          font-size: 0.9em;
        }
      }
    }

    .articles-grid {
      grid-template-columns: 1fr !important;
    }
  }
}

@media screen and (max-width: 576px) {
  .layout-container .category-container {
    max-width: 500px;
    padding: 48px 12px 24px;

    .articles-wrapper {
      .article-card {
        .article-cover {
          height: 160px;
        }

        .article-info {
          padding: 16px;

          .article-title {
            font-size: 1.1em;
          }

          .article-summary {
            font-size: 0.85em;
            -webkit-line-clamp: 2;
          }

          .article-meta {
            font-size: 0.8em;
          }
        }
      }
    }
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .layout-container .category-container {
    .categories-wrapper,
    .article-card {
      background: rgba(255, 255, 255, 0.1);
    }

    .article-info {
      .article-title {
        color: #e2e8f0;
      }

      .article-summary {
        color: #94a3b8;
      }

      .article-meta {
        color: #64748b;
      }
    }
  }
}
</style>
